var api = require("../../utils/getApiUrl")
var app = getApp();
var util = require("../../utils/util")

//  引入MQTT
var mqtt = require('../../utils/mqtt.min.js')

//  配置MQTT连接参数
var client = null



Page({
  data: {
    uid: "",
    token: "",
    IMEI: "",
    name: "",
    online: "",
    tmp: 0,
    addr: "",
    state: 0,
    showColor: "#515151",
    showOnline: "",
    showState: "",
    jdqs: [1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1],
    selected: 0,
    reaminNumber: -1,
    maxTempBtnTitle: "",
    maxTempBtnImg: "",
    minTempBtnTitle: "",
    minTempBtnImg: "",
    from: "",
    shutDownDevicesBtnImg: "../../image/power1.png"
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(e) {
    wx.stopPullDownRefresh()
    var from = e.from
    console.log(e.from);

    let data = app.globalData.selectedDev
    console.log(data);
    this.setData({
      uid: app.globalData.userInfo.uid,
      token: app.globalData.userInfo.token,
      IMEI: data.imei,
      name: data.name,
      online: data.online,
      tmp: data.tmp,
      addr: data.addr,
      state: data.state,
      isSwapperFanOpen: false,
      isHeatOpen: false,
      isCoolFanOpen: false,
      isFireOpen: false,
      startDevBtnImg: "",
      startDevBtnTitle: "",
      startFireBtnImg: "",
      startFireBtnTitle: "",
      reaminNumber: data.reaminNumber,
      maxTempBtnTitle: "",
      maxTempBtnImg: "",
      minTempBtnTitle: "",
      minTempBtnImg: "",
      from: from
    })

    if (this.data.reaminNumber == 0) {
      wx.showModal({
        title: "次数不足",
        content: "请购买设备使用次数",
        complete() {
          wx.navigateBack();
        }
      })
      return
    }

    //  更新界面UI
    this.updateUI()

    //  告知设备进入设备控制页面
    if (this.data.from == 'code') {
      this.devGoToCtlPage()
    }
  },

  onReady() {
    var that = this
    wx.showLoading({ "title": "正在连接设备" })
    //  创建clientId
    const clientId = `wx_${app.globalData.userInfo.uid}`
    const host = 'www.lyuiot.top'
    const qos = 0
    const port = '8084'
    // const connectUrl = `wxs://${host}:${port}/mqtt`
    const connectUrl = `wxs://${host}/mqtt`

    // const connectUrl = `mqtts://${host}:${port}/mqtt`

    // const connectUrl = `mqtt://broker.emqx.io:1883`

    const pub_topic = `p/${this.data.IMEI}/pub`

    //  配置MQTT使用
    client = mqtt.connect(connectUrl, {
      clientId,
      clean: true,
      connectTimeout: 4000,
      reconnectPeriod: 1000,
      keepalive: 60, //60s ，表示心跳间隔
      username: 'emqx_test',
      password: 'emqx_test',
    })

    client.on('connect', () => {
      console.log("MQTT建立连接成功");

      //  订阅主题
      client.subscribe(pub_topic, (err) => {
        if (!err) {
          wx.hideLoading()
          wx.showToast({ title: "连接成功" })
        }
      })
    })

    client.on('message', function (topic, message) {
      // message is Buffer -- 解析状态
      that.parseMessage(message)
    })

    client.on('disconnect', function (topic, message) {
      // message is Buffer -- 解析状态
      wx.navigateBack()
    })

  },
  //  消息解析
  parseMessage(message) {
    let tenArr = new Uint8Array(message)

    //  校验消息格式
    if (tenArr.length != 19 || tenArr[0] != 255 || tenArr[1] != 85) {
      //  消息错误 -> 返回
      return
    }

    // 功能码选择
    switch (tenArr[2]) {
      case 3:
        //  上报状态 -> 更新状态 -> tmp jdqs
        this.updateSourceDate(tenArr[4] * 256 + tenArr[5], Array.from(tenArr.slice(7)))
        break;
      case 9:
        //  次数减少 -> 服务结束 -> 返回上一页
        wx.showToast({
          title: "本次服务结束", success: () => {
            setTimeout(() => {
              wx.navigateBack()
            }, 1200);
          }
        })
        break;

      default:
        //  功能码错误 -> 返回
        return;
    }

  },

  updateSourceDate(tmp: number, jdqs: Array<number>) {
    directParseDeviceState(jdqs)

    var state: number = directParseDeviceState(jdqs)
    console.log("本机解析状态: ", state);

    this.setData({
      jdqs: jdqs,
      tmp: tmp,
      state: state
    })

    this.updateUI()
  },

  goToBuy() {
    wx.navigateTo({ url: "../postReport/postReport?type=1" })
  },

  goToReport() {
    wx.navigateTo({ url: `../postReport/postReport?IMEI=${this.data.IMEI}&type=0` })
  },

  ctrlDevDirectionStart(e) {
    var selected = e.currentTarget.dataset.id

    //  若设备离线不执行操作
    if (this.data.online == "0") {
      return
    }

    this.setData({
      selected: selected
    })

    console.log("触摸开始");
    //  开启打开指定编号继电器
    this.setRelay(selected, 1)
  },

  ctrlDevDirectionEnd(e) {
    //  若设备离线不执行操作
    if (this.data.online == "0") {
      return
    }

    var selected = e.currentTarget.dataset.id

    this.setData({
      selected: 0
    })
    setTimeout(() => {
      this.setRelay(selected, 0)
    }, 200);
  },

  //  方向控制按钮事件
  ctrlDevDirection(e) {
    console.log(e.currentTarget.dataset.id);
    console.log(e);

    let selected = e.currentTarget.dataset.id

    //  若设备离线不执行操作
    if (this.data.online == "0") {
      return
    }
    //  开启打开指定编号继电器
    this.setRelay(selected, 1)

    //  延时关闭指定编号继电器
    setTimeout(() => {
      this.setRelay(selected, 0)
    }, 200);
  },

  ctrlPowerOffStart() {
    this.setData({
      shutDownDevicesBtnImg: '/image/pwoer.png'
    })
  },

  //  控制设备结束使用
  ctrlPowerOffEnd() {
    this.setData({
      shutDownDevicesBtnImg: '/image/power1.png'
    })
    wx.showModal({
      title: "您确定要关闭设备吗?", success: (res) => {
        if (res.confirm == true) {
          console.log("发送执行结束设备操作");
          ctlDev('stopDev', this.data.uid, this.data.token, this.data.IMEI)
          wx.navigateBack()
        }
      }
    })
  },

  //  控制点火
  ctrlFireBtn() {
    //  判断在线
    if (this.data.online == '0') {
      wx.showToast({ title: "设备未上线", icon: "error" })
      return
    }

    if (this.data.state == '0') {
      console.log("启动设备");
      wx.showToast({ title: "请启动外设", icon: "error" })
    } else if (this.data.state == '1' || this.data.state == '3') {
      ctlDev('startFire', this.data.uid, this.data.token, this.data.IMEI)
    } else if (this.data.state == '2') {
      ctlDev('stopFire', this.data.uid, this.data.token, this.data.IMEI)
    } else {
      wx.showToast({ title: "操作失败", icon: "error" })
    }
  },

  //  控制外设启停
  ctrlDevBtn() {
    if (this.data.online == '0') {
      wx.showToast({ title: "设备未上线", icon: "error" })
      return
    }
    if (this.data.state == '0' || this.data.state == '3') {
      console.log("启动设备");
      ctlDev('startDev', this.data.uid, this.data.token, this.data.IMEI)
    } else if (this.data.state == '1') {
      console.log("关闭设备");
      ctlDev('stopDev', this.data.uid, this.data.token, this.data.IMEI)
    } else if (this.data.state == '2') {
      wx.showToast({ title: "需关闭点火", icon: "error" })
    } else {
      wx.showToast({ title: "操作失败", icon: "error" })
    }
  },
  //控制最高温度
  ctrlMaxBtn() {
    wx.showModal({
      title: '提示',
      editable: true,
      placeholderText: "请输入最大温度",
      success: (res) => {
        var temp = Number(res.content)
        //判断温度范围是否有误
        if (temp >= 0 && temp <= 500) {
          //发送请求
          wx.request({
            url: api.setMaxTemp(),
            method: "GET",
            header: {
              "content-type": "application/x-www-form-urlencoded"
            },
            data: {
              IMEI: this.data.IMEI,
              maxtmp: temp,
              uid: this.data.uid,
              token: this.data.token
            },
            success: (res) => {
              console.log(res)
              if (res.data.code == 1) {
                wx.showToast({
                  title: '设置成功',
                  icon: 'success',
                  duration: 1200
                })
              } else {
                wx.showToast({
                  title: '请求失败',
                  icon: 'error',
                  duration: 1200
                })
              }
            },
            fail: () => {
              wx.showToast({
                title: '连接失败',
                icon: 'error',
                duration: 1200
              })
            }
          })
        }
        //温度范围有误
        else {
          wx.showToast({
            title: '数值有误',
            icon: 'error',
            duration: 1200
          })
        }

      }
    })
  },
  //控制最低温度
  ctrlMinBtn() {
    wx.showModal({
      title: '提示',
      editable: true,
      placeholderText: "请输入点火温度",
      success: (res) => {
        var temp = Number(res.content)
        //判断温度范围是否发送请求
        if (temp >= 0 && temp <= 500) {
          //发送请求
          wx.request({
            url: api.setMinTemp(),
            method: "GET",
            header: {
              "content-type": "application/x-www-form-urlencoded"
            },
            data: {
              IMEI: this.data.IMEI,
              mintmp: temp,
              uid: this.data.uid,
              token: this.data.token
            },
            success: (res) => {
              if (res.data.code == 1) {
                wx.showToast({
                  title: '设置成功',
                  icon: 'success',
                  duration: 1200
                })
              } else {
                wx.showToast({
                  title: '请求失败',
                  icon: 'error',
                  duration: 1200
                })
              }
            },
            fail: () => {
              wx.showToast({
                title: '连接失败',
                icon: 'error',
                duration: 1200
              })
            }
          })
        }
        //数值有误
        else {
          wx.showToast({
            title: '数值有误',
            icon: 'error',
            duration: 1200
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getRelayInfo()
    setInterval(() => {
      this.getRelayInfo()
    }, 30000)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    client.end()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.getRelayInfo()
  },

  //  更新页面视图
  updateUI() {
    //  更新文字
    this.setData({
      showOnline: util.getShowOnline(this.data.online),
      showState: util.getShowState(this.data.state),
      showColor: util.getShowColor(this.data.online, this.data.state),
    })
    //  更新图标
    this.parseDeviceState()
  },

  //  解析外设状态
  parseDeviceState() {
    let arr = this.data.jdqs

    var isSwapperFanOpen = false
    var isHeatOpen = false
    var isCoolFanOpen = false
    var isFireOpen = false
    var startDevBtnImg = "../../image/f1.png"
    var startFireBtnImg = "../../image/d11.png"
    var startDevBtnTitle = "一键启动"
    var startFireBtnTitle = "启动点火"
    var maxTempBtnTitle = "最高温度"
    var maxTempBtnImg = "../../image/wenduzengjia.png"
    var minTempBtnTitle = "点火温度"
    var minTempBtnImg = "../../image/wendujiangdi.png"

    //  是否在线
    if (this.data.online == "1") {
      if (arr[6] === 1) {
        isHeatOpen = true
        console.log("yes");

      }
      if (arr[7] === 1) {
        isSwapperFanOpen = true
      }
      if (arr[8] === 1) {
        isCoolFanOpen = true
      }
      if (arr[9] === 1 || arr[10] === 1 || arr[11] === 1) {
        isFireOpen = true
      }

      if (this.data.state == '1' || this.data.state == '2') {
        startDevBtnImg = "../../image/f2.png"
        startDevBtnTitle = "停止启动"
      }

      if (isFireOpen == true) {
        startFireBtnImg = "../../image/d12.png"
        startFireBtnTitle = "停止点火"
      }
    }

    this.setData({
      isSwapperFanOpen: isSwapperFanOpen,
      isHeatOpen: isHeatOpen,
      isCoolFanOpen: isCoolFanOpen,
      isFireOpen: isFireOpen,
      startDevBtnImg: startDevBtnImg,
      startFireBtnImg: startFireBtnImg,
      startDevBtnTitle: startDevBtnTitle,
      startFireBtnTitle: startFireBtnTitle,
      maxTempBtnTitle: maxTempBtnTitle,
      maxTempBtnImg: maxTempBtnImg,
      minTempBtnTitle: minTempBtnTitle,
      minTempBtnImg: minTempBtnImg
    })
  },

  //  告知设备,进入控制页面
  devGoToCtlPage() {
    wx.request({
      url: api.devGoToCtlPage(),
      method: "GET",
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      data: {
        uid: app.globalData.userInfo.uid,
        token: app.globalData.userInfo.token,
        IMEI: this.data.IMEI,
        ctl: 1
      },
      success: (res) => {
        console.log("555555555555555" + res);
      },
      fail: () => {
        wx.hideLoading()
        wx.showToast({
          title: "请求失败",
          icon: "error"
        })
      }
    })
  },

  //  获取寄存器状态
  getRelayInfo() {
    wx.request({
      url: api.getRelayInfo(),
      method: "GET",
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      data: {
        uid: app.globalData.userInfo.uid,
        token: app.globalData.userInfo.token,
        IMEI: this.data.IMEI
      },
      success: (res) => {
        console.log(res.data.data);
        if (res.data.code === 1) {
          this.setData({
            jdqs: res.data.data.jdqs,
            online: res.data.data.online,
            state: res.data.data.state,
            tmp: res.data.data.tmp
          })
          this.updateUI()
        }
      },
      fail: () => {
        wx.hideLoading()
        wx.showToast({
          title: "请求失败",
          icon: "error"
        })
      }
    })
  },

  //  设置继电器状态
  setRelay(index: number, ctl: number) {
    wx.showLoading()
    wx.request({
      url: api.setRelay(),
      method: "GET",
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      data: {
        uid: app.globalData.userInfo.uid,
        token: app.globalData.userInfo.token,
        IMEI: this.data.IMEI,
        index: index,
        ctl: ctl
      },
      fail: () => {
        wx.hideLoading()
        wx.showToast({
          title: "请求失败",
          icon: "error"
        })
      },
      success: (res) => {
        console.log(res.data);
        wx.hideLoading()
        if (res.data.code === 1) {
          console.log(res.data.data);
        } else {
          wx.showToast({ title: res.data.msg, icon: "error" })
        }
      }
    })
  },
})

//  设备控制
function ctlDev(ctl: String, uid: String, token: String, IMEI: String) {
  var url = api.stopDev()

  switch (ctl) {
    case "stopDev":
      url = api.stopDev()
      break;
    case "startDev":
      url = api.startDev()
      break;
    case "startFire":
      url = api.startFire()
      break;
    case "stopFire":
      url = api.stopFire()
      break;
    default:
      return;
  }

  wx.request({
    url: url,
    method: "GET",
    header: {
      "content-type": "application/x-www-form-urlencoded"
    },
    data: {
      uid: uid,
      token: token,
      IMEI: IMEI
    },
    success: (res) => {
      let code = res.data.code
      let msg = res.data.msg
      console.log(res)
      wx.hideLoading()
      if (code == 1) {
        wx.showToast({
          title: msg
        })
      } else {
        wx.showToast({
          title: msg,
          icon: "error"
        })
      }
    },
    fail: () => {
      wx.hideLoading()
      wx.showToast({
        title: "请求失败",
        icon: "error"
      })
    }
  })
}

//  MQTT 直接解析设备状态
function directParseDeviceState(JDQs: Array<number>) {
  let key = JDQs[7] + JDQs[8] + JDQs[9] + JDQs[10] + JDQs[11]
  switch (key) {
    case 0: return 0
    case 2:
      if (JDQs[6] == 1) // 加热状态
        return 1;
      else {
        return 3; // 冷却状态
      }
    case 5: return 2;
  }
  return -1;
}